import pygame

from bullet import Bullet
from pygame.sprite import Sprite


class Ship(Sprite):
    """管理飞船的类"""
    def __init__(self, ai_game):
        """初始化飞船并设置其初始位置"""
        super().__init__()
        self.screen = ai_game.screen
        self.settings = ai_game.settings
        self.screen_rect = ai_game.screen.get_rect()

        # 加载飞船图像及获取外接矩形
        self.image = pygame.image.load(
            'PythonPrograming/project/alien_invasion/images/ship.bmp')
        self.rect = self.image.get_rect()

        # 对每艘新飞船，都放置在屏幕底部中央
        self.center_ship()

        # # 暂时存储位置参数（为了保留小数部分）
        # self.x = float(self.rect.x)

        # 移动标志
        self.moving_right = False
        self.moving_left = False
        self.moving_up = False
        self.moving_down = False

        # 存储子弹的编组
        self.bullets = pygame.sprite.Group()
        self.bullets_allowed = self.settings.bullets_allowed
        self.shooting = False
        self.shooting_count = 0

    def blitme(self):
        """在指定位置绘制飞船"""
        self.screen.blit(self.image, self.rect)
        for bullet in self.bullets:
            bullet.draw_bullet()

    def update(self):
        """根据移动标志调整飞船位置"""
        # 暂时存储位置参数（为了保留小数部分）
        self.x = float(self.rect.x)
        self.y = float(self.rect.y)
        if self.moving_right:
            self.x += self.settings.ship_speed
        if self.moving_left:
            self.x -= self.settings.ship_speed
        if self.moving_up:
            self.y -= self.settings.ship_speed
        if self.moving_down:
            self.y += self.settings.ship_speed
        # 更新飞船坐标
        self.rect.x = self.x
        self.rect.y = self.y
        # 穿过边界
        if self.screen.get_rect().right < self.rect.left:
            self.rect.x = -self.rect.width
        elif 0 > self.rect.right:
            self.rect.x = self.settings.screen_width
        if self.screen.get_rect().bottom < self.rect.bottom:
            self.rect.bottom = self.screen.get_rect().bottom
        elif self.screen.get_rect().top > self.rect.top:
            self.rect.top = self.screen.get_rect().top

        # 射击
        if self.shooting and self.bullets_allowed == 0:
            self._shoot()
        # 绘制子弹
        self.bullets.update()

    def _shoot(self):
        """创建子弹，加入编组"""
        # 降低子弹发射频率
        self.shooting_count += 1
        allow = self.bullets_allowed
        if allow > 0 and len(self.bullets) < allow:
            self.bullets.add(Bullet(self))
        elif self.shooting_count >= self.settings.bullet_shooting_speed:
            self.bullets.add(Bullet(self))
            self.shooting_count = 0

    def center_ship(self, midbottom=None):
        '''重置飞船位置'''
        self.rect.midbottom = (midbottom or self.screen_rect.midbottom)
